package com.forrest.web.data;

import com.forrest.web.common.model.User;
import com.jfinal.core.Controller;
import com.jfinal.upload.UploadFile;

import java.io.File;

public class DataController extends Controller {

    private static DataService service = new DataService();

    public void index() {
        setAttr("blogPage", service.display());
        render("index.html");
    }

    public void search() {
        String search = getPara("search");
        setAttr("blogPage", service.search(search));
        render("result.html");
    }

    public void delete() {
        service.delete(getParaToInt());
        redirect("/data");
    }

    public void edit() {
        setAttr("user", service.findById(getParaToInt()));
        render("edit.html");
    }

    public void add() {
        getModel(User.class).save();
        redirect("/data");
    }

    public void update() {
        UploadFile uploadFile = getFile("headsculpture");
        User user = service.findById(getParaToInt("user.id"));
        String pwd = getPara("user.pwd");
        String salt = getPara("user.salt");
        if (!pwd.equals(salt)) {
            renderText("两次密码输入不一致");
        } else {
            File file = uploadFile.getFile();
            String headName = user.getUsername() + uploadFile.getFileName();
            File file1 = new File(file.getParent(), "/" + headName);
            if (!file.renameTo(file1)) {
                renderText("文件上传失败");
            } else if (!user.setPwd(pwd).setSalt(salt).setHeadsculp(headName).update()) {
                renderText("未知错误");
            } else {
                redirect("/data");
            }
        }
    }

    public void upload() {


    }
}
